package com.alageek.personalblog.web;

import com.alageek.personalblog.entity.doo.User;
import com.alageek.personalblog.service.RoleService;
import com.alageek.personalblog.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

/**
 * 登录注册控制器
 * @author AlaGeek
 */
@Slf4j
@Controller
@RequestMapping("/")
public class LoginController {

    private final UserService userService;
    private final RoleService roleService;

    public LoginController(UserService userService, RoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/register")
    public String register(){
        return "register";
    }

    @PostMapping("/doRegister")
    public String doRegister(User user){
        log.debug("User: {}", user);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setCreateTime(new Date());
        user.setUpdateTime(user.getCreateTime());
        userService.saveSelective(user);
        roleService.saveUserRoleRelationship(user.getId(), 2);
        return "login";
    }

    @GetMapping("/index")
    public String index() {
        return "index";
    }

}
